/*
 * Basirudin Rachman - 2011
 * b@rachmans.com
 * 
 */

using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Imtihan.Web;

namespace Imtihan
{
    public partial class Exam : Page
    {
        ImtihanDomainContext _context = new ImtihanDomainContext();

        public Exam()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            cbExam.ItemsSource = _context.Assessments;
            _context.Load(_context.GetAssessmentsQuery());
        }

        ObservableCollection<UserAssessmentScheduleView> _userAssessmentScheduleViews = new ObservableCollection<UserAssessmentScheduleView>();
        bool _isRegistered = false;

        void loadGrid(string id)
        {
            _userAssessmentScheduleViews = new ObservableCollection<UserAssessmentScheduleView>();
            _isRegistered = false;
            Guid assessmentId = Guid.Parse(id);
            _context.GetAssessmentSchedulesByAssessmentId(assessmentId, (op) =>
            {
                if (op != null)
                {
                    foreach (AssessmentSchedule assessmentSchedule in op.Value)
                    {
                        UserAssessmentScheduleView userAssessmentScheduleView = new UserAssessmentScheduleView
                        {
                            AssessmentSchedule = new AssessmentSchedule
                            {
                                Capacity = assessmentSchedule.Capacity,
                                Id = assessmentSchedule.Id,
                                StartDateTime = assessmentSchedule.StartDateTime,
                                Name = assessmentSchedule.Name,
                                EndDateTime = assessmentSchedule.EndDateTime
                            }
                        };

                        _context.GetUserAssessmentSchedulesByAssessmentScheduleId(assessmentSchedule.Id, (op1) =>
                        {
                            if (op1 != null)
                            {
                                userAssessmentScheduleView.AssessmentSchedule.Capacity -= op1.Value.Count;
                                userAssessmentScheduleView.TakeExamVisibility = Visibility.Collapsed;

                                if (!_isRegistered)
                                {
                                    userAssessmentScheduleView.Command = op1.Value.Where(uaSched => uaSched.UserId.ToLower()
                                        == UserManager.Instance.Id.ToLower()).FirstOrDefault() != null ? ButtonTextConstant.UNREGISTER : ButtonTextConstant.REGISTER;
                                    userAssessmentScheduleView.IsCommandable = true;

                                    if (userAssessmentScheduleView.Command == ButtonTextConstant.UNREGISTER)
                                    {
                                        _isRegistered = true;

                                        //  Check date and time if in between start and end time then VISIBLE.
                                        if (userAssessmentScheduleView.AssessmentSchedule.StartDateTime <= DateTime.Now 
                                            && userAssessmentScheduleView.AssessmentSchedule.EndDateTime >= DateTime.Now)
                                        {
                                            userAssessmentScheduleView.TakeExamVisibility = Visibility.Visible;
                                        }
                                        
                                        foreach (UserAssessmentScheduleView addedUserAssessmentScheduleView in _userAssessmentScheduleViews)
                                        {
                                            addedUserAssessmentScheduleView.IsCommandable = false;
                                        }
                                    }
                                }
                                else
                                {
                                    userAssessmentScheduleView.Command = ButtonTextConstant.REGISTER;
                                    userAssessmentScheduleView.IsCommandable = false;
                                }
                            }

                            _userAssessmentScheduleViews.Add(userAssessmentScheduleView);
                        }, null);

                    }

                    dgSchedule.ItemsSource = _userAssessmentScheduleViews;
                }
            }, null);
        }

        private void cbExam_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            loadGrid((sender as ComboBox).SelectedValue.ToString());
        }

        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            UserAssessmentScheduleView vw = dgSchedule.SelectedItem as UserAssessmentScheduleView;
            switch ((sender as Button).Content.ToString())
            {
                case ButtonTextConstant.REGISTER:
                    _context.UserAssessmentSchedules.Add(new UserAssessmentSchedule
                    {
                        Id = Guid.NewGuid(),
                        AssessmentScheduleId = vw.AssessmentSchedule.Id
                        ,
                        UserId = UserManager.Instance.Id
                    });

                    _context.SubmitChanges((op) =>
                    {
                        if (!op.HasError)
                        {
                            loadGrid(cbExam.SelectedValue.ToString());
                        }
                    }, null);
                    break;
                case ButtonTextConstant.UNREGISTER:
                    _context.Load(_context.GetUserAssessmentSchedulesQuery(), (opLoad) =>
                                {
                                    if (!opLoad.HasError)
                                    {
                                        UserAssessmentSchedule newUserAssessmentSchedule = opLoad.Entities.Where(uas => uas.AssessmentScheduleId == vw.AssessmentSchedule.Id
                                    && uas.UserId.ToLower() == UserManager.Instance.Id.ToLower()).FirstOrDefault();
                                        _context.UserAssessmentSchedules.Remove(newUserAssessmentSchedule);
                                        _context.SubmitChanges((opSubmit) =>
                                        {
                                            if (!opSubmit.HasError)
                                            {
                                                loadGrid(cbExam.SelectedValue.ToString());
                                            }
                                        }, null);
                                    }
                                }, null);
                    break;
            }
        }

        private void btnTakeExam_Click(object sender, RoutedEventArgs e)
        {
            UserAssessmentScheduleView vw = dgSchedule.SelectedItem as UserAssessmentScheduleView;
            _context.Load(_context.GetAssessmentSchedulesQuery(), (opLoad) =>
            {
                if (!opLoad.HasError)
                {
                    AssessmentSchedule assessmentSchedule = opLoad.Entities.Where(asSched => asSched.Id == vw.AssessmentSchedule.Id).FirstOrDefault();
                    if (assessmentSchedule != null)
                    {
                        this.NavigationService.Navigate(new Uri(string.Format("/ExamProblem?AssessmentId={0}", assessmentSchedule.AssessmentId), UriKind.Relative));
                    }
                }
            }, null);
        }

    }
}
